import time
import os
from jqexception.jqexecption import OverlordErr

import logging

from wuxianshang.raffle import conn

logger = logging.getLogger("log")


class CacheLock(object):
    def __init__(self, expires=60, wait_timeout=10):
        self.cache = conn
        self.expires = expires  # 函数执行超时时间
        self.wait_timeout = wait_timeout  # 拿锁等待超时时间。

    # 设置锁
    def get_lock(self, lock_key, user_uuid, expires):
        if self.cache.set(lock_key, user_uuid, expires):
            return True
        raise OverlordErr

    def exit_raffle(self, lock_key, user_uuid):
        lock_value = self.cache.get(lock_key)
        if lock_value is None or lock_value == "":
            return True
        elif lock_value == user_uuid:
            return True
        return False

    # 校验该箱子是否存在锁
    def exit_lock(self, lock_key):
        lock_value = self.cache.get(lock_key)
        if lock_value is None or lock_value == "":
            return False
        return True

    # 更新持有锁用户的过期时间
    def expire_lock(self, lock_key, user_uuid, expires):
        try:
            self.cache.expire(lock_key, expires)
        except:
            logger.error(f"can not change cache Lock, uuid={user_uuid}")
            return False
        return True

    # 校验当前持有锁的user是否等于请求的user
    def check_lock_user(self, lock_key, user_uuid):
        lock_value = self.cache.get(lock_key)
        if lock_value == user_uuid:
            return True
        return False

    def release_lock(self, lock_key, identifier):
        lock_value = self.cache.get(lock_key)
        if lock_value == identifier:
            self.cache.delete(lock_key)

    # 获取当前锁的剩余时间
    def ttl_lock(self, lock_key):
        result = self.cache.ttl(lock_key)
        ttl_second = 0
        if result is None:
            return ttl_second
        return result
